import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { VbenFormSchema } from '#/adapter/form';
import type { OnActionClickFn } from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';
import { formatDateTime } from '@vben/utils';

import { h } from 'vue';
import { z } from '#/adapter/form';
import { getDeptSelects, getDeptTree } from '#/api/system/dept';
import { $t } from '#/locales';

// 获取弹出容器
function getPopupContainer() {
  return document.body;
}

/**
 * 获取编辑表单的字段配置。如果没有使用多语言，可以直接export一个数组常量
 */
export function useSchema(): VbenFormSchema[] {
  return [
    {
      component: 'Input',
      fieldName: 'name',
      label: $t('system.dept.deptName'),
      rules: z
        .string()
        .min(2, $t('ui.formRules.minLength', [$t('system.dept.deptName'), 2]))
        .max(
          50,
          $t('ui.formRules.maxLength', [$t('system.dept.deptName'), 50]),
        ),
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        api: getDeptTree,
        class: 'w-full',
        checkStrictly: true, // 允许选择任何节点
        afterFetch: (data: SystemDeptApi.SystemDept[]) => {
          // 处理每个节点，确保正确显示
          const processNode = (node: SystemDeptApi.SystemDept) => {
            // 添加label属性，存储显示文本
            const newNode = {
              ...node,
              label: node.name,
            };

            // 如果有子节点，递归处理
            if (node.children && node.children.length > 0) {
              newNode.children = node.children.map(child => processNode(child));
            }

            return newNode;
          };

          return data.map(item => processNode(item));
        },
        filterTreeNode(input: string, node: any) {
          if (!input || input.length === 0) {
            return true;
          }
          const name: string = node.name ?? '';
          return name.includes(input);
        },
        getPopupContainer,
        labelField: 'label',
        showSearch: true,
        treeDefaultExpandAll: true,
        valueField: 'id',
        childrenField: 'children',
      },
      fieldName: 'parentId',
      label: $t('system.dept.parentDept'),
      renderComponentContent() {
        return {
          title({ label, status }: { label: string; status: number }) {
            const coms = [];
            if (!label) return '';

            const textColor = status === 0 ? 'text-red-500' : '';
            coms.push(h('span', { class: textColor }, label));

            return h('div', { class: 'flex items-center gap-1' }, coms);
          },
        };
      },
    },
    {
      component: 'Input',
      fieldName: 'code',
      label: $t('system.dept.code'),
      rules: z
        .string()
        .max(50, $t('ui.formRules.maxLength', [$t('system.dept.code'), 50]))
        .optional(),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.enabled'), value: 1 },
          { label: $t('common.disabled'), value: 0 },
        ],
        optionType: 'button',
      },
      defaultValue: 1,
      fieldName: 'status',
      label: $t('system.dept.status'),
    },
    {
      component: 'Textarea',
      componentProps: {
        maxLength: 500,
        rows: 3,
        showCount: true,
      },
      fieldName: 'remark',
      label: $t('system.dept.remark'),
      rules: z
        .string()
        .max(500, $t('ui.formRules.maxLength', [$t('system.dept.remark'), 500]))
        .optional(),
    },
  ];
}

/**
 * 获取表格列配置
 * @description 使用函数的形式返回列数据而不是直接export一个Array常量，是为了响应语言切换时重新翻译表头
 * @param onActionClick 表格操作按钮点击事件
 */
export function useColumns(
  onActionClick?: OnActionClickFn<SystemDeptApi.SystemDept>,
): VxeTableGridOptions<SystemDeptApi.SystemDept>['columns'] {
  return [
    {
      align: 'left',
      field: 'name',
      fixed: 'left',
      title: $t('system.dept.deptName'),
      treeNode: true,
      width: 180,
    },
    {
      field: 'code',
      title: $t('system.dept.code'),
      width: 120,
    },
    {
      cellRender: {
        name: 'CellTag',
        props: {
          statusOptions: [
            { status: 1, text: $t('common.enabled'), type: 'success' },
            { status: 0, text: $t('common.disabled'), type: 'error' },
          ],
        },
      },
      field: 'status',
      title: $t('system.dept.status'),
      width: 100,
    },
    {
      field: 'createdTime',
      title: $t('system.dept.createTime'),
      width: 180,
      formatter: ({ cellValue }: { cellValue: string }) => {
        return formatDateTime(cellValue);
      }
    },
    {
      field: 'remark',
      title: $t('system.dept.remark'),
    },
    {
      align: 'right',
      cellRender: {
        attrs: {
          nameField: 'name',
          nameTitle: $t('system.dept.name'),
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          {
            code: 'append',
            text: $t('system.dept.addSubDept'),
          },
          {
            code: 'edit',
            text: '编辑',
          },
          {
            code: 'delete',
            text: '删除',
            type: 'danger',
          },
        ],
      },
      field: 'operation',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      title: $t('system.dept.operation'),
      width: 200,
    },
  ];
}
